package cn.edu.cqie.config;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.edu.cqie.enums.RespToAppEnum;
import cn.edu.cqie.utils.BizException;
import cn.edu.cqie.utils.CommonConstant;

@Aspect
@Component
public class LoginAspect {

	private final static Logger logger = LoggerFactory.getLogger(LoginAspect.class);

	@Pointcut("execution(* cn.edu.cqie.controller..*.*(..))")
	public void logPointCut() {
	}

	/**
	 * 环绕通知 @Around ， 当然也可以使用 @Before (前置通知) @After (后置通知)
	 * 
	 * @param point
	 * @return
	 * @throws Throwable
	 */
	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {

		// 获取类名+方法名
		String method = point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName();

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String token = request.getHeader("Authorization");
		System.out.println(token);

		// 如果当前方法非登陆方法，判断token
		if (!CommonConstant.LOGINMETHOD.equals(method)) {

			if (!StringUtils.hasText(token)) {
				logger.error(RespToAppEnum.BADREQUEST.getMessage() + ":" + "token不能为空");
				return ResultBean.error(RespToAppEnum.BADREQUEST.getCode(),
						RespToAppEnum.BADREQUEST.getMessage() + ":" + "token不能为空");
			}
			try {
				// 暂时停止校验
				
				
				
				/*
				 * if (JwtTokenUtil.isExpiration(token, CommonConstant.BASE64SECRET)) {
				 * logger.error(RespToAppEnum.TOKEN_EXPIRED.getMessage()); return
				 * ResultBean.error(RespToAppEnum.TOKEN_EXPIRED); }
				 */
			} catch (BizException e) {
				logger.error(e.getMessage());
				return ResultBean.error(e.getCode(), e.getMessage());
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage());
				return ResultBean.error(RespToAppEnum.TOKEN_ERROR);
			}

		}

		return point.proceed();
	}

}
